package com.maiji.cloud.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.maiji.cloud.entities.login.*;
import com.maiji.cloud.entities.shopingmall.WithdrawalAmountLimitConfigEntity;
import com.maiji.cloud.request.login.*;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.login.*;
import com.maiji.cloud.service.*;
import com.maiji.cloud.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.controller.DietController;
import com.maiji.cloud.mapper.DietLogMapper;
import com.maiji.cloud.mapper.FoodMaterialCollectionMapper;
import com.maiji.cloud.mapper.FoodMaterialMapper;
import com.maiji.cloud.mapper.FoodMaterialTypeLableMapper;
import com.maiji.cloud.mapper.LabelMapper;
import com.maiji.cloud.mapper.LabelMiddleFoodMaterialMapper;
import com.maiji.cloud.mapper.NutrientContentMapper;
import com.maiji.cloud.mapper.UploadRecordMapper;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.ReqMetaData;
import com.maiji.cloud.request.SaveURBelongIdReqDto;
import com.maiji.cloud.response.BaseResDto;
import com.maiji.cloud.response.login.DietLogResDto.DietLogResInnerData;
import com.maiji.cloud.response.Status;

/**
 * 饮食相关 Description:
 * 
 * @author zhanglr
 * @date 2019年6月14日
 */
@Service
@Transactional
public class DietServiceImpl extends ServiceImpl<DietLogMapper,DietLog> implements DietService {

	private static final Logger logger = LoggerFactory.getLogger(DietController.class);
	@Autowired
	private RedisTemplate<String, Object> maiji1RedisTemplate;
    @Autowired
    private AppUserService appUserService;
	@Autowired
	private UploadRecordMapper uploadRecordMapper;
	@Autowired
	private UploadRecordService uploadRecordService;
	@Autowired
	private DietLogMapper dietLogMapper;
	@Autowired
	private FoodMaterialMapper foodMaterialMapper;
	@Autowired
	private FoodMaterialService foodMaterialService;
	@Autowired
	private NutrientContentMapper nutrientContentMapper;
	@Autowired
	private LabelMiddleFoodMaterialMapper labelMiddleFoodMaterialMapper;
	@Autowired
	private LabelMiddleFoodMaterialService labelMiddleFoodMaterialService;
	@Autowired
	private FoodMaterialTypeLableMapper foodMaterialTypeLableMapper;
	@Autowired
	private FoodMaterialTypeLableService foodMaterialTypeLableService;
	@Autowired
	private FoodMaterialCollectionMapper foodMaterialCollectionMapper;
	@Autowired
	private LabelMapper labelMapper;
    @Autowired
    private FoodMaterialTypeLableService foodTypeService;
    @Autowired
    DietService dietService;
    @Autowired
	private MongoTemplate mongoTemplate;


	@Override
	public BaseResDto addDietLog(AddDietLogResDto addDietLogResDto) throws Exception {
		logger.info("DietServiceImpl.addDietLog,addDietLogResDto is {}", JSON.toJSONString(addDietLogResDto));

		// 获得用户id
		AppUser appUser = appUserService.checkToken(addDietLogResDto.getData().getMaijiToken());

		if (appUser == null) {
			logger.info("UserServiceImpl.addDietLog,appUser is {}", JSON.toJSONString(appUser));
			return BaseResDto.baseResDto(Status.PARAMETERERROR, "token 无效 ");
		}
		
		if((addDietLogResDto.getData().getImgIds() == null || addDietLogResDto.getData().getImgIds().size() < 1) && StringUtils.isBlank(addDietLogResDto.getData().getContent())) 
		return new BaseResDto(Status.ERROR);
		
		//当天是否记录的早中晚餐
		EntityWrapper<DietLog>  entityWrapper = new EntityWrapper<DietLog>();
		entityWrapper.eq("user_id", appUser.getUuId());
		entityWrapper.eq("type", addDietLogResDto.getData().getType());
		entityWrapper.ge("in_time",TimeUtil.date2String(new Date(), "yyyy-MM-dd"));
		
		DietLog dietLog = dietService.selectOne(entityWrapper);
		if(dietLog != null) {
			dietLogMapper.deleteById(dietLog.getUuId());
			EntityWrapper<UploadRecord> uploadRecordWrapper = new EntityWrapper<UploadRecord>();
			uploadRecordWrapper.eq("belong_id", dietLog.getUuId());
			uploadRecordMapper.delete(uploadRecordWrapper);
		}

		dietLog = new DietLog();
		BeanUtils.copyProperties(addDietLogResDto.getData(), dietLog);
		dietLog.setUserId(appUser.getUuId());
		String uuId = UUID_MD5.getUUID();
		dietLog.setUuId(uuId);
		dietLog.setInTime(new Date());

		dietLogMapper.insert(dietLog);
		
		if(addDietLogResDto.getData().getImgIds() == null || addDietLogResDto.getData().getImgIds().size() < 1 )return new BaseResDto(Status.SUCCESS);
		List<UploadRecord> listUploadRecord = uploadRecordMapper.selectBatchIds(addDietLogResDto.getData().getImgIds());
	
		ArrayList<SaveURBelongIdReqDto> listSaveURBelongIdReqDto = new ArrayList<SaveURBelongIdReqDto>();
		for(UploadRecord uploadRecord : listUploadRecord) {
			SaveURBelongIdReqDto saveURBelongIdReqDto = new SaveURBelongIdReqDto();
			saveURBelongIdReqDto.setBelongId(uuId);
			saveURBelongIdReqDto.setImageId(uploadRecord.getUuId());
			listSaveURBelongIdReqDto.add(saveURBelongIdReqDto);
		}
		if(listSaveURBelongIdReqDto.size() > 0) {
			uploadRecordMapper.updateBelongIdWithImages(listSaveURBelongIdReqDto);
		}
		
		return new BaseResDto(Status.SUCCESS);
	}

	@Override
	public FoodTypeLableResDto searchFoodMaterial(String typeId, String laybleId, String name) {
        List<FoodMaterialTypeLable> foodTypes = foodMaterialTypeLableService.selectList(new EntityWrapper<FoodMaterialTypeLable>().eq("parent_id", typeId));
        List<String> foodTypeIds = foodTypes.parallelStream().map(FoodMaterialTypeLable::getUuId).collect(Collectors.toList());
        List<String> foodIds = Lists.newArrayList();
        if (StringUtil.isNotBlank(laybleId)) foodIds = labelMiddleFoodMaterialService.selectList(
                new EntityWrapper<LabelMiddleFoodMaterial>().eq("label_id", laybleId))
                .parallelStream().map(LabelMiddleFoodMaterial::getFoodMaterialId).collect(Collectors.toList());
        EntityWrapper<FoodMaterialEntity> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("type_label_id", foodTypeIds);
        if (foodIds.size() > 0) entityWrapper.in("uu_id", foodIds);
        if (StringUtil.isNotBlank(name)) entityWrapper.like("name", name);
        List<FoodMaterialEntity>foods = foodMaterialService.selectList(entityWrapper);
        List<FoodTypeLableResData> foodTypeResList = Lists.newArrayList();
        if (foods.size() > 0) {
            foodIds = foods.parallelStream().map(FoodMaterialEntity::getUuId).collect(Collectors.toList());
            List<UploadRecord> uploadRecords = uploadRecordService.selectList(new EntityWrapper<UploadRecord>().in("belong_id", foodIds).eq("is_main", 1));
            List<FoodMaterialResData> foodResDataList = BaseService.dealWithOneToOne(foods, "getUuId",
                    FoodMaterialResData.class, "setImgData", uploadRecords, "getBelongId", UploadImageResData.class);
            foodTypeResList = BaseService.dealWithOneToMany(foodTypes, "getUuId", FoodTypeLableResData.class,
                    "setList", foodResDataList, "getTypeLabelId", FoodMaterialResData.class);
        }

        return new FoodTypeLableResDto(Status.SUCCESS).setData(foodTypeResList);
	}

	@Override
	public DietLogResDto getDietLog(GetDietLogReqDto getDietLogReqDto) throws Exception {

		logger.info("DietServiceImpl.getDietLog,param is {}", JSON.toJSONString(getDietLogReqDto));
		// 获得用户id
		AppUser appUser = appUserService.checkToken(getDietLogReqDto.getData().getMaijiToken());

		if (appUser == null) {
			logger.info("UserServiceImpl.getDietLog,appUser is {}", JSON.toJSONString(appUser));
			return new DietLogResDto(Status.PARAMETERERROR);

		}
		DietLogResDto dietLogResDto = new DietLogResDto(Status.SUCCESS);
		DietLogResInnerData dietLogResInnerData = dietLogResDto.dataInstance();

		if (!StringUtils.isEmpty(getDietLogReqDto.getData().getTime())) {
			Date selectedDate = TimeUtil.stringToDate(getDietLogReqDto.getData().getTime(), "yyyy-MM-dd");
			Date Time = TimeUtil.getBefordayTime(selectedDate, 1, 0);
			List<DietLog> befodayList = dietLogMapper.getDietLogByUserId(appUser.getUuId(), selectedDate, Time);
			dietLogResInnerData.setTodyList(getListDietLogResData(befodayList));
			dietLogResDto.setData(dietLogResInnerData);
			return dietLogResDto;
		}

		Date todyTime = TimeUtil.getZeroTime(null);
		List<DietLog> todyList = dietLogMapper.getDietLogByUserId(appUser.getUuId(), todyTime, null);
		
		

		dietLogResInnerData.setTodyList(getListDietLogResData(todyList));
		Date date = new Date();
		Date yesterdayTime = TimeUtil.getBefordayTime(date, 1, 1);

		List<DietLog> yesterdayList = dietLogMapper.getDietLogByUserId(appUser.getUuId(), yesterdayTime, todyTime);
		dietLogResInnerData.setYesterdayList(getListDietLogResData(yesterdayList));

		Date befodayTime = TimeUtil.getBefordayTime(date, 2, 1);

		List<DietLog> befodayList = dietLogMapper.getDietLogByUserId(appUser.getUuId(), befodayTime, yesterdayTime);
		dietLogResInnerData.setBeforeYesterdayList(getListDietLogResData(befodayList));

		dietLogResDto.setData(dietLogResInnerData);

		return dietLogResDto;
	}

	private List<DietLogResData> getListDietLogResData(List<DietLog> list) {

		List<DietLogResData> listDietLogResData = new ArrayList<DietLogResData>();
		
		
		for (DietLog dietLog : list) {
			DietLogResData dietLogResData = new DietLogResData();
			BeanUtils.copyProperties(dietLog, dietLogResData);
			dietLogResData.setDietLogId(dietLog.getUuId());
			listDietLogResData.add(dietLogResData);
			List<UploadImageResData> imgDatas = new ArrayList<UploadImageResData>();
			List<UploadRecord>  listUploadRecord = uploadRecordMapper.selectListByBelongId(dietLog.getUuId());
			for(UploadRecord uploadRecord : listUploadRecord) {
				UploadImageResData uploadImageResData = new UploadImageResData();
				BeanUtils.copyProperties(uploadRecord, uploadImageResData);
				imgDatas.add(uploadImageResData);
				
			}
			dietLogResData.setImgDatas(imgDatas);
		}

		return listDietLogResData;

	}

	@Override
	public FoodTypeLableResDto getFoodmaterialTypeLable() {
		/**
		 * 查询父级id是0的
		 */
		List<FoodMaterialTypeLable> list = foodMaterialTypeLableMapper.selectListByParentId("0");

		FoodTypeLableResDto foodTypeLableResDto = new FoodTypeLableResDto(Status.SUCCESS);

		List<FoodTypeLableResData> listFoodTypeLableResData = new ArrayList<FoodTypeLableResData>();

		for (FoodMaterialTypeLable foodMaterialTypeLable : list) {
			FoodTypeLableResData foodTypeLableResData = new FoodTypeLableResData();
			BeanUtils.copyProperties(foodMaterialTypeLable, foodTypeLableResData);
			listFoodTypeLableResData.add(foodTypeLableResData);

		}
		foodTypeLableResDto.setData(listFoodTypeLableResData);

		return foodTypeLableResDto;
	}

	@Override
	public BaseDataResDto<List<FoodMaterialResData>> foodMaterialCollectionList(String token, ReqMetaData reqMetaData) {
		
		logger.info("DietServiceImpl.foodMaterialCollectionList,reqMetaData is {}，token is {}", JSON.toJSONString(reqMetaData),token);
		// 获得用户id
		AppUser appUser = appUserService.checkToken(token);

		if (appUser == null) {
			logger.info("UserServiceImpl.getDietLog,appUser is {}", JSON.toJSONString(appUser));
			return new BaseDataResDto<List<FoodMaterialResData>>(Status.PARAMETERERROR);

		}
		Integer start = (reqMetaData.getPage() - 1) * reqMetaData.getSize();
		
		List<FoodMaterialCollection> listFoodMaterialCollection = foodMaterialCollectionMapper.selectListByUserId(appUser.getUuId(), start, reqMetaData.getSize());
		
		List<FoodMaterialResData> listFoodMaterialCollectionResData = new ArrayList<FoodMaterialResData>() ;
		
		for(FoodMaterialCollection  foodMaterialCollection : listFoodMaterialCollection) {
			FoodMaterialResData foodMaterialCollectionResData = new FoodMaterialResData();
			BeanUtils.copyProperties(foodMaterialCollection, foodMaterialCollectionResData);
			foodMaterialCollectionResData.setUuId(foodMaterialCollection.getFoodMaterialId());
			foodMaterialCollectionResData.setIsCollection(1);//已被收藏
			
			List<UploadRecord>  listUploadRecord = uploadRecordMapper.selectListByBelongId(foodMaterialCollection.getFoodMaterialId());
			UploadImageResData imgData = new UploadImageResData();
			if(listUploadRecord.size() >0 ) {
				BeanUtils.copyProperties(listUploadRecord.get(0), imgData);
				imgData.setSmallUrl(imgData.getUrl()+""+CommonStringValueEnum.IMAGE_URL_SMALL.getValue());
				foodMaterialCollectionResData.setImgData(imgData);
			}
			NutrientContentEntity nutrientContentEntity = nutrientContentMapper.selectOneByElementName(foodMaterialCollection.getFoodMaterialId(), "热量");
			
			Integer sum = foodMaterialCollectionMapper.getSumByfoodMaterialId(foodMaterialCollection.getFoodMaterialId());
			foodMaterialCollectionResData.setCount(sum);
			if(nutrientContentEntity != null) {
				foodMaterialCollectionResData.setHot(nutrientContentEntity.getValue());
			}
			
			
			listFoodMaterialCollectionResData.add(foodMaterialCollectionResData);
		}
		
		BaseDataResDto<List<FoodMaterialResData>>  foodMaterialCollectionResDto = new BaseDataResDto<List<FoodMaterialResData>> (Status.SUCCESS);
		foodMaterialCollectionResDto.setData(listFoodMaterialCollectionResData);
		return foodMaterialCollectionResDto;
	}

	@Override
	public BaseResDto thumbsfoodMaterial(String token, ThumbsfoodMaterialReqDto param) {

		logger.info("DietServiceImpl.thumbsfoodMaterial,param is {}，token is {}", JSON.toJSONString(param),token);
		// 获得用户id
		AppUser appUser = appUserService.checkToken(token);

		if (appUser == null) {
			logger.info("UserServiceImpl.getDietLog,appUser is {}", JSON.toJSONString(appUser));
			return BaseResDto.baseResDto(Status.PARAMETERERROR,"token无效");

		}
		FoodMaterialCollection foodMaterialCollection = foodMaterialCollectionMapper.thumbsfoodMaterial(appUser.getUuId(),param.getData().getUuId());
		
		if(foodMaterialCollection != null){
			 
			Integer isDel = (foodMaterialCollection.getIsDel() == CommonIntValueEnum.FOOD_MATERIAL_COLLECTION_IS_DES_NOT.getValue())? CommonIntValueEnum.FOOD_MATERIAL_COLLECTION_IS_DES_IS.getValue() : CommonIntValueEnum.FOOD_MATERIAL_COLLECTION_IS_DES_NOT.getValue();
			foodMaterialCollection.setIsDel(isDel);
			foodMaterialCollectionMapper.updateAllColumnById(foodMaterialCollection);
			
		return new BaseResDto(Status.SUCCESS);
		
		}
		foodMaterialCollection = new FoodMaterialCollection();
		FoodMaterialEntity foodMaterialEntity = foodMaterialMapper.selectOneById(param.getData().getUuId());
		
		BeanUtils.copyProperties(foodMaterialEntity, foodMaterialCollection);
		
		NutrientContentEntity nutrientContentEntity = nutrientContentMapper.selectOneByElementName(foodMaterialEntity.getUuId(), "热量");
		
		foodMaterialCollection.setUuId(UUID_MD5.getUUID());
		foodMaterialCollection.setInTime(new Date());
		foodMaterialCollection.setFoodMaterialId(foodMaterialEntity.getUuId());
		foodMaterialCollection.setUserId(appUser.getUuId());
		foodMaterialCollection.setIsDel(CommonIntValueEnum.FOOD_MATERIAL_COLLECTION_IS_DES_NOT.getValue());
		List<UploadRecord> listImgs = uploadRecordMapper.selectListByBelongId(foodMaterialEntity.getUuId());
		if(listImgs != null && listImgs.size() > 0) foodMaterialCollection.setImgUrl(listImgs.get(0).getUrl());
		if(nutrientContentEntity != null) {
			foodMaterialCollection.setHot(nutrientContentEntity.getValue());
		}
		
		
		foodMaterialCollectionMapper.insert(foodMaterialCollection);
		return new BaseResDto(Status.SUCCESS);
	}
	@Override
	public FoodTypeLableResDto searchFoodMaterialByName(BaseDataReqDto<String> param) {
		logger.info("DietServiceImpl.searchFoodMaterialByName,param is {}", JSON.toJSONString(param));

		String foodMaterialName = param.getData();
		FoodTypeLableResDto foodTypeLableResDto = new FoodTypeLableResDto(Status.SUCCESS);
		List<FoodTypeLableResData> listFoodTypeLableResData = new ArrayList<FoodTypeLableResData>();
		// 根据食材名字获取二级分类标签id集合

		List<String> typeLableIds = foodMaterialMapper.getTypeLableIds(foodMaterialName);
		
		if(typeLableIds == null || typeLableIds.size() <= 0) return new FoodTypeLableResDto(Status.SUCCESS).setData(listFoodTypeLableResData);
		List<FoodMaterialTypeLable> listFoodMaterialTypeLable = foodTypeService.selectList( new EntityWrapper<FoodMaterialTypeLable>().in("uu_id", typeLableIds));
		
		
		Map<String,List<FoodMaterialEntity>> map = foodMaterialMapper.selectList(new EntityWrapper<FoodMaterialEntity>().in("type_label_id", typeLableIds)
				.like("name", foodMaterialName, SqlLike.DEFAULT).or().like("alias", foodMaterialName, SqlLike.DEFAULT)).stream().collect(Collectors.groupingBy(FoodMaterialEntity::getTypeLabelId));
		
		for(FoodMaterialTypeLable foodMaterialTypeLable : listFoodMaterialTypeLable) {
			FoodTypeLableResData foodTypeLableResData = new FoodTypeLableResData();
			BeanUtils.copyProperties(foodMaterialTypeLable, foodTypeLableResData);
			List<FoodMaterialResData> list = map.get(foodMaterialTypeLable.getUuId()).stream().map(foodMaterial -> {
				FoodMaterialResData foodMaterialResData = new FoodMaterialResData();
                BeanUtils.copyProperties(foodMaterial, foodMaterialResData);
                List<UploadRecord> listUploadRecord = uploadRecordMapper
						.selectListByBelongId(foodMaterial.getUuId());
				UploadImageResData imgData = new UploadImageResData();
				if (listUploadRecord.size() > 0) {
					BeanUtils.copyProperties(listUploadRecord.get(0), imgData);
					imgData.setSmallUrl(imgData.getUrl() + "" + CommonStringValueEnum.IMAGE_URL_SMALL.getValue());
					foodMaterialResData.setImgData(imgData);
				}
				//根据食材id获取阶段
				List<LabelMiddleFoodMaterial> listLabelMiddleFoodMaterial = labelMiddleFoodMaterialMapper.selectListByFoodMaterialId(foodMaterial.getUuId());
				List<String> listString = new ArrayList<String>();
				for(LabelMiddleFoodMaterial labelMiddleFoodMaterial : listLabelMiddleFoodMaterial) {
					listString.add(labelMiddleFoodMaterial.getLabelId());
				}
				if(listString.size() > 0) {
					List<Label> listLable = labelMapper.getLabelsByIds(listString);
					foodMaterialResData.setLabelList(listLable);
				}
				
				
				
                return foodMaterialResData;
            }).collect(Collectors.toList());
			foodTypeLableResData.setList(list);
			listFoodTypeLableResData.add(foodTypeLableResData);
			
		}
		foodTypeLableResDto.setData(listFoodTypeLableResData);
		
		return foodTypeLableResDto;
	}

	@Override
	public BaseDataResDto<List<DietLogDaysListResData>> getDietLogDaysList(GetDietLogReqDto getDietLogReqDto) throws Exception {
		logger.info("DietServiceImpl.getDietLogDaysList,param is {}", JSON.toJSONString(getDietLogReqDto));
		// 获得用户id
		AppUser appUser = appUserService.checkToken(getDietLogReqDto.getData().getMaijiToken());

		if (appUser == null) {
			logger.info("UserServiceImpl.getDietLog,appUser is {}", JSON.toJSONString(appUser));
			return new BaseDataResDto(Status.PARAMETERERROR);
		}
		
		BaseDataResDto<List<DietLogDaysListResData>> reponse =  new BaseDataResDto<List<DietLogDaysListResData>>(Status.SUCCESS);
		List<DietLogDaysListResData> dietLogDaysListResData = new ArrayList<DietLogDaysListResData>();
		Date startTime = TimeUtil.stringToDate(getDietLogReqDto.getData().getStartTime(), "yyyy-MM-dd");
		Date endTime = TimeUtil.getBefordayTime(TimeUtil.stringToDate(getDietLogReqDto.getData().getEndtTime(), "yyyy-MM-dd"), 1, 0);
		List<DietLog> list = dietLogMapper.getDietLogByUserId(appUser.getUuId(), startTime, endTime);
		List<DietLogResData> listDietLogResData = list.stream().map(dietLog -> {
			DietLogResData dietLogResData = new DietLogResData();
			BeanUtils.copyProperties(dietLog, dietLogResData);
			dietLogResData.setDietLogId(dietLog.getUuId());
			List<UploadImageResData> imgDatas = new ArrayList<UploadImageResData>();
			List<UploadRecord>  listUploadRecord = uploadRecordMapper.selectListByBelongId(dietLog.getUuId());
			for(UploadRecord uploadRecord : listUploadRecord) {
				UploadImageResData uploadImageResData = new UploadImageResData();
				BeanUtils.copyProperties(uploadRecord, uploadImageResData);
				imgDatas.add(uploadImageResData);
				
			}
			dietLogResData.setImgDatas(imgDatas);
			return dietLogResData;
			
		}).collect(Collectors.toList());
		//Map<Date, List<DietLog>> map = list.stream().collect(Collectors.groupingBy(DietLog :: getInTime));
		Map<String, List<DietLogResData>> map = listDietLogResData.stream().collect(Collectors.groupingBy(dietLog -> {
			String time = null;
			try {
				time = TimeUtil.date2String(dietLog.getInTime(),"yyyy-MM-dd");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return time;
		}));
		
		 ListIterator<Map.Entry<String, List<DietLogResData>>> li = new ArrayList<Map.Entry<String, List<DietLogResData>>> (map.entrySet()).listIterator(map.size());
		    
		    while(li.hasPrevious()) {  
		    	Map.Entry<String, List<DietLogResData>> entry = li.previous();
		    	DietLogDaysListResData dietLogDaysResData = new DietLogDaysListResData();
		    	dietLogDaysResData.setTime(entry.getKey());
		    	dietLogDaysResData.setList(entry.getValue());
		    	dietLogDaysListResData.add(dietLogDaysResData);
		    }
		    reponse.setData(dietLogDaysListResData);
		
		return reponse;
	}

	@Override
	public BaseResDto cancelCollectionFoodMaterial(List<String> foodMaterialids, String token) {
		AppUser appUser = RedisUtil.getAppUserByRedis(maiji1RedisTemplate, MyRedisConfig.REDISDATABASENO, token, appUserService);
		String userId = appUser.getUuId();
		  EntityWrapper<FoodMaterialCollection> entityWrapper = new EntityWrapper<FoodMaterialCollection>();
	        entityWrapper.eq("user_id", userId);
	        if (foodMaterialids == null || foodMaterialids.size() == 0)
	        	foodMaterialids = foodMaterialCollectionMapper.selectList(entityWrapper).parallelStream().map(FoodMaterialCollection::getFoodMaterialId).collect(Collectors.toList());
	        if (foodMaterialids.size() == 0) return new BaseResDto(Status.SUCCESS);
	        entityWrapper.in("food_material_id", foodMaterialids);
	        if (foodMaterialCollectionMapper.delete(entityWrapper)<= 0) return new BaseResDto(Status.ERROR.setMessage("批量删除用户收藏食材失败"));
		
		return new BaseResDto(Status.SUCCESS);
	}

	@Override
	public BaseResDto deleteDielogById(List<String> dielogId) {
		if(dielogId == null || dielogId.size() < 1) return new BaseResDto(Status.PARAMETERERROR);
		dietLogMapper.deleteBatchIds(dielogId);
		return new BaseResDto(Status.SUCCESS);
	}

	@Override
	public BaseResDto newVersionAddDietLog(AddDietLogResDto addDietLogResDto) throws Exception {
		logger.info("DietServiceImpl.addDietLog,addDietLogResDto is {}", JSON.toJSONString(addDietLogResDto));

		// 获得用户id
		AppUser appUser = appUserService.checkToken(addDietLogResDto.getData().getMaijiToken());

		if (appUser == null) {
			logger.info("UserServiceImpl.addDietLog,appUser is {}", JSON.toJSONString(appUser));
			return BaseResDto.baseResDto(Status.PARAMETERERROR, "token 无效 ");
		}
		
		if((addDietLogResDto.getData().getImgIds() == null || addDietLogResDto.getData().getImgIds().size() < 1) && StringUtils.isBlank(addDietLogResDto.getData().getContent())) 
		return new BaseResDto(Status.ERROR);
		
		EntityWrapper<DietLog>  entityWrapper = new EntityWrapper<DietLog>();
		entityWrapper.eq("user_id", appUser.getUuId());
		entityWrapper.eq("type", addDietLogResDto.getData().getType());
		entityWrapper.ge("in_time",TimeUtil.date2String(new Date(), "yyyy-MM-dd"));
		
		List<DietLog> dietLogs = dietService.selectList(entityWrapper);
		AddDielogLimitEntity addDielogLimitEntity = mongoTemplate.findOne(
				new Query(Criteria.where("type").is(CommonIntValueEnum.ADD_DEILOG_LIMIT_TYPE.getValue())),
				AddDielogLimitEntity.class, AddDielogLimitEntity.TABLE_NAME);
		if(addDielogLimitEntity != null && dietLogs != null && addDielogLimitEntity.getAmount() < dietLogs.size())return new BaseResDto(Status.USER_WORNING_INFO, "每餐最多记录"+addDielogLimitEntity.getAmount()+"次"); 
		DietLog dietLog = new DietLog();
		BeanUtils.copyProperties(addDietLogResDto.getData(), dietLog);
		dietLog.setUserId(appUser.getUuId());
		String uuId = UUID_MD5.getUUID();
		dietLog.setUuId(uuId);
		dietLog.setInTime(new Date());

		dietLogMapper.insert(dietLog);
		
		if(addDietLogResDto.getData().getImgIds() == null || addDietLogResDto.getData().getImgIds().size() < 1 )return new BaseResDto(Status.SUCCESS);
		List<UploadRecord> listUploadRecord = uploadRecordMapper.selectBatchIds(addDietLogResDto.getData().getImgIds());
	
		ArrayList<SaveURBelongIdReqDto> listSaveURBelongIdReqDto = new ArrayList<SaveURBelongIdReqDto>();
		for(UploadRecord uploadRecord : listUploadRecord) {
			SaveURBelongIdReqDto saveURBelongIdReqDto = new SaveURBelongIdReqDto();
			saveURBelongIdReqDto.setBelongId(uuId);
			saveURBelongIdReqDto.setImageId(uploadRecord.getUuId());
			listSaveURBelongIdReqDto.add(saveURBelongIdReqDto);
		}
		if(listSaveURBelongIdReqDto.size() > 0) {
			uploadRecordMapper.updateBelongIdWithImages(listSaveURBelongIdReqDto);
		}
		
		return new BaseResDto(Status.SUCCESS);
	}

	@Override
	public BaseDataResDto<List<DietLogDaysListResData>> newVersionGetDietLogDaysList(
			GetDietLogReqDto getDietLogReqDto) throws Exception {
		logger.info("DietServiceImpl.newVersionGetDietLogDaysList,param is {}", JSON.toJSONString(getDietLogReqDto));
		// 获得用户id
		AppUser appUser = appUserService.checkToken(getDietLogReqDto.getData().getMaijiToken());

		if (appUser == null) {
			logger.info("UserServiceImpl.newVersionGetDietLogDaysList,appUser is {}", JSON.toJSONString(appUser));
			return new BaseDataResDto(Status.PARAMETERERROR);
		}
		
		BaseDataResDto<List<DietLogDaysListResData>> reponse =  new BaseDataResDto<List<DietLogDaysListResData>>(Status.SUCCESS);
		List<DietLogDaysListResData> dietLogDaysListResData = new ArrayList<DietLogDaysListResData>();
		Date startTime = TimeUtil.stringToDate(getDietLogReqDto.getData().getStartTime(), "yyyy-MM-dd");
		Date endTime = TimeUtil.getBefordayTime(TimeUtil.stringToDate(getDietLogReqDto.getData().getEndtTime(), "yyyy-MM-dd"), 1, 0);
		List<DietLog> list = dietLogMapper.getDietLogByUserId(appUser.getUuId(), startTime, endTime);
		List<DietLogResData> listDietLogResData = list.stream().map(dietLog -> {
			DietLogResData dietLogResData = new DietLogResData();
			BeanUtils.copyProperties(dietLog, dietLogResData);
			dietLogResData.setDietLogId(dietLog.getUuId());
			List<UploadImageResData> imgDatas = new ArrayList<UploadImageResData>();
			List<UploadRecord>  listUploadRecord = uploadRecordMapper.selectListByBelongId(dietLog.getUuId());
			for(UploadRecord uploadRecord : listUploadRecord) {
				UploadImageResData uploadImageResData = new UploadImageResData();
				BeanUtils.copyProperties(uploadRecord, uploadImageResData);
				imgDatas.add(uploadImageResData);
				
			}
			dietLogResData.setImgDatas(imgDatas);
			return dietLogResData;
			
		}).collect(Collectors.toList());
		//Map<Date, List<DietLog>> map = list.stream().collect(Collectors.groupingBy(DietLog :: getInTime));
		Map<String, List<DietLogResData>> map = listDietLogResData.stream().collect(Collectors.groupingBy(dietLog -> {
			String time = null;
			try {
				time = TimeUtil.date2String(dietLog.getInTime(),"yyyy-MM-dd");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return time;
		}));
		
		 ListIterator<Map.Entry<String, List<DietLogResData>>> li = new ArrayList<Map.Entry<String, List<DietLogResData>>> (map.entrySet()).listIterator(map.size());
		    
		
		    while(li.hasPrevious()) {  
		    	Map.Entry<String, List<DietLogResData>> entry = li.previous();
		    	DietLogDaysListResData dietLogDaysResData = new DietLogDaysListResData();
		    	dietLogDaysResData.setTime(entry.getKey());
		    	
		    	Map<Integer, List<DietLogResData>> mapType = entry.getValue().stream().collect(Collectors.groupingBy(dietLog -> {
					return dietLog.getType();
				}));
		    	
		    	ListIterator<Map.Entry<Integer, List<DietLogResData>>> liIterator = new ArrayList<Map.Entry<Integer, List<DietLogResData>>> (mapType.entrySet()).listIterator(mapType.size());
		    	List<NewVersionGetDietLogDaysListData> listNewVersionGetDietLogDaysListData = new ArrayList<NewVersionGetDietLogDaysListData>();
		    	while(liIterator.hasPrevious()) {  
		    		  Map.Entry<Integer, List<DietLogResData>> entry2 = liIterator.previous();
		    		  NewVersionGetDietLogDaysListData newVersionGetDietLogDaysListData = new NewVersionGetDietLogDaysListData();
		    		  newVersionGetDietLogDaysListData.setType(entry2.getKey());
		    		  newVersionGetDietLogDaysListData.setList(entry2.getValue());
		    		  listNewVersionGetDietLogDaysListData.add(newVersionGetDietLogDaysListData);
		    	  }
		    	dietLogDaysResData.setListData(listNewVersionGetDietLogDaysListData);
		    	
//		    	DietLogDaysListResData dietLogDaysResData = new DietLogDaysListResData();
//		    	dietLogDaysResData.setTime(entry.getKey());
//		    	dietLogDaysResData.setList(entry.getValue());
		    	dietLogDaysListResData.add(dietLogDaysResData);
		    }
		    reponse.setData(dietLogDaysListResData);
		
		return reponse;
		
	}
}